import React, { useState } from 'react';
import { Form, Input, DatePicker, Table } from 'antd';
import { history } from 'umi'
import { Pagination, AdvancedSearch } from '@/components';
import moment from 'moment';
import { CopyText } from '@/pages/Task/components';
import CompanyDepart from '@/components/CompanyDepart';
import { getUserOrgInfo } from '@/utils/utils';
import { useScoreTaskList } from '../../../hooks';
import styles from '../index.less';
import { getFormatDateCondition } from '../../../utils';

const { RangePicker } = DatePicker;

const AbandonScore = ({ form, location }) => {
    const { getFieldDecorator, getFieldsValue } = form;
    const { query: urlQuery } = location;
    const { firstCompanyCode } = getUserOrgInfo();
    const [query, setQuery] = useState({
        scoreState: [2],
        executorCompanyCode: firstCompanyCode,
        taskNo: urlQuery.taskNo || '',
        taskName: urlQuery.taskName || '',
        executeEmployeeName: urlQuery.executeEmployeeName || '',
        createTimeStart: urlQuery.createTimeStart || '',
        createTimeEnd: urlQuery.createTimeEnd || '',
        orderByField: urlQuery.orderByField || '',
        pageNo: urlQuery.pageNo || 1,
        pageSize: urlQuery.pageSize || 10
    });

    // 更新url及query
    const routerReplace = newQuery => {
        history.push({
            query: {
                ...urlQuery,
                ...newQuery
            }
        });
        setQuery({
            ...query,
            ...newQuery
        });
    };
    // 分页操作
    const handlePaginationChange = _pagination => {
        const { current, ...rest } = _pagination;
        routerReplace({
            ...rest,
            pageNo: current
        });
    };
    // 过滤排序
    const handleTableChange = async (pagination, filters, sorter) => {
        let orderByField = '';
        if (sorter && sorter.field && sorter.order) {
            orderByField = `${sorter.field}|${sorter.order.replace('end', '')}`;
        }
        routerReplace({
            orderByField
        });
    };

    const [taskLoading, taskData, taskTotal] = useScoreTaskList(query);

    const defaultSort = (type, def) => {
        const { orderByField = '' } = urlQuery;
        const str = orderByField ? orderByField.replace(`${type}|`, '').trim() : '';
        if (str === 'asc') {
            return 'ascend';
        }
        if (str === 'desc') {
            return 'descend';
        }
        return def;
    };

    const columns = [
        {
            title: '任务编号',
            dataIndex: 'taskNo',
            width: 150,
            render: text => <CopyText text={text} />
        },
        {
            title: '任务名称',
            dataIndex: 'taskName',
            render: text => (
                <div
                    style={{
                        width: '100%',
                        minWidth: 200,
                        position: 'relative'
                    }}
                >
                    <span
                        style={{
                            position: 'absolute',
                            left: 0,
                            right: 0,
                            top: 0,
                            transform: 'translateY(-50%)',
                            overflow: 'hidden',
                            whiteSpace: 'nowrap',
                            textOverflow: 'ellipsis'
                        }}
                        title={text}
                    >
                        {text}
                    </span>
                </div>
            )
        },
        {
            title: '执行人',
            dataIndex: 'taskExecutor',
            width: 100
        },
        {
            title: '所属部门',
            dataIndex: 'executorDepartmentName',
            width: 150
        },
        {
            title: '发起评分时间',
            dataIndex: 'createTime',
            width: 150,
            sorter: () => {},
            sortOrder: defaultSort('createTime'),
            render: text => (text ? moment(text).format('YYYY-MM-DD HH:mm') : '')
        },
        {
            title: '放弃评分时间',
            dataIndex: 'finishTime',
            sortOrder: defaultSort('finishTime'),
            width: 150,
            sorter: () => {},
            render: text => (text ? moment(text).format('YYYY-MM-DD HH:mm') : '')
        }
    ];

    const getParams = () => {
        const param = getFieldsValue();
        const { createTime, companyDept, ...rest } = param;
        const [createTimeStart, createTimeEnd] = getFormatDateCondition(createTime);
        const { companyId, departmentId } = companyDept;
        return {
            ...rest,
            executorCompanyCode: companyId,
            executorDepartmentCode: departmentId,
            createTimeStart,
            createTimeEnd
        };
    };
    const handleSubmit = () => {
        routerReplace({
            ...getParams(),
            pageNo: 1
        });
    };

    const handelReset = () => {
        handleSubmit();
    };

    React.useEffect(() => {
        const { taskNo, taskName, executeEmployeeName, createTimeStart, createTimeEnd } = query;
        form.setFieldsValue({
            taskNo: taskNo || '',
            taskName: taskName || '',
            executeEmployeeName: executeEmployeeName || '',
            createTime: createTimeStart && createTimeEnd ? [moment(createTimeStart), moment(createTimeEnd)] : []
        });
    }, []);
    const initCompanyDepart = query.executorCompanyCode ? { companyId: query.executorCompanyCode } : undefined;

    return (
        <>
            <AdvancedSearch form={form} onSubmit={handleSubmit} onReset={handelReset}>
                <Form.Item label="任务编号">
                    {getFieldDecorator('taskNo', {
                        initialValue: ''
                    })(<Input placeholder="请输入任务编号" allowClear />)}
                </Form.Item>
                <Form.Item label="任务名称">
                    {getFieldDecorator('taskName', {
                        initialValue: ''
                    })(<Input placeholder="请输入任务名称" allowClear />)}
                </Form.Item>
                <Form.Item label="执行人">
                    {getFieldDecorator('executeEmployeeName', {
                        initialValue: ''
                    })(<Input placeholder="请输入执行人" allowClear />)}
                </Form.Item>
                <Form.Item label="发起评分时间">
                    {getFieldDecorator('createTime', {
                        initialValue: []
                    })(
                        <RangePicker
                            dropdownClassName={styles.rangePicker}
                            ranges={{
                                本周: [moment().startOf('week'), moment().endOf('week')],
                                本月: [moment().startOf('month'), moment().endOf('month')],
                                本季度: [moment().startOf('quarter'), moment().endOf('quarter')]
                            }}
                        />
                    )}
                </Form.Item>
                <Form.Item label="所属部门" className={styles.temp}>
                    {getFieldDecorator('companyDept', { initialValue: initCompanyDepart })(
                        <CompanyDepart needPermission={false} />
                    )}
                </Form.Item>
            </AdvancedSearch>
            <Table
                rowKey="id"
                rowClassName={styles.tableRow}
                bordered={false}
                columns={columns}
                loading={taskLoading}
                // 发起评分时间搜索时用creatTime, 展示时取scoreCreateTime的值
                // 放弃评分时间搜索时用finishTime, 展示时取scoreTime的值
                dataSource={taskData.map(item => ({
                    ...item,
                    createTime: item.scoreCreateTime,
                    finishTime: item.scoreTime
                }))}
                onChange={handleTableChange}
                pagination={false}
                scroll={{ x: 'max-content' }}
                onRow={record => ({
                    onClick: () => {
                        history.push({
                            pathname: '/work/task/taskdetail',
                            query: { id: record.id || '', activeKey: 'scoreRec' },
                            state: { tabRoute: true, tabRefresh: true }
                        });
                    }
                })}
            />
            <Pagination
                total={taskTotal}
                current={Number(query.pageNo)}
                pageSize={Number(query.pageSize)}
                onChange={handlePaginationChange}
                loading={taskLoading}
            />
        </>
    );
};

export default Form.create()(AbandonScore);
